package cn.com.aiouyi.config;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

/**
 * Created by tommy on 2018/3/27.
 */
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleConfig implements WebMvcConfigurer {

	@Value("${spring.messages.basenames}")  
    private String basenames;
	@Value("${spring.messages.encoding}")  
	private String encoding;
	
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认语言
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
    
    /**
     * 语言包资源
     * @return
     */
    @Bean
    public MessageSource messageSource() {
    	ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
    	reloadableResourceBundleMessageSource.setUseCodeAsDefaultMessage(true);
    	reloadableResourceBundleMessageSource.setDefaultEncoding(encoding);
    	String[] messagesBaseNames = new String[]{};
    	if(StringUtils.isNotEmpty(basenames)){
    		messagesBaseNames = basenames.split(",");
    	}
    	reloadableResourceBundleMessageSource.setBasenames(messagesBaseNames);
        return reloadableResourceBundleMessageSource;
    }
}